package ai.easy.robot.task

import kotlinx.coroutines.experimental.*
import kotlin.coroutines.experimental.CoroutineContext

class MainWork(val cctx:CoroutineContext = CommonPool, val work:()->Unit) {

    private var job: Job? = null

    fun start(){
        job = launch(cctx){
            isPaused = false
            work()
        }
    }

    fun stop(){
        job?.cancel()
    }

    private var isPaused = false
    private var wannaPaused = false

    fun pause(){
        wannaPaused = true
        //
        runBlocking(cctx) {
            while (!isPaused) {
                delay(20)
            }
        }
    }

    fun resume(){
        wannaPaused = false
        isPaused = false
    }

    fun suspendWhenPaused(){
        isPaused = wannaPaused
        if(!wannaPaused) return
        //
        runBlocking(cctx) {
            while (isPaused) {
                delay(20)
            }
        }
    }
}